package com.yzg.simple.netty.websoket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author misterWei
 * @mailbox mynameisweiyan@gmail.com
 *
 * 基于Netty 实现的长连接的全双工的交互
 * 全双工: 双方即时通讯.
 *
 * 说明 webSocket 是Http的升级版,状态为101 协议 ws: 或者 websocket: 开头
 *
 */
public class NettyWebSoketServer {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap()
                             .option(ChannelOption.SO_BACKLOG,128)
                              .childOption(ChannelOption.SO_KEEPALIVE,true)
                               .handler(new LoggingHandler(LogLevel.INFO))
                                .channel(NioServerSocketChannel.class)
                                  .group(bossGroup,workerGroup)
                                    .childHandler(new NettyWebSoketServerInitlializer());
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            channelFuture.addListener((g)->{
                if (g.isSuccess()) {
                    System.out.println("WebSocket 服务器启动成功!!");
                }
            });
            channelFuture.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
